<template>
  <div>
    <MainHead searchDescribe="请输入" @searchChange="getSearchValue" namespace @namespaceChange="getNamespaceValue"
      @namespaceList="getNamespaceList" @dataList="getData" add @addFunc="handleAdd" />
    <el-card shadow="never" class="border-0">
      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="getData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
        <template v-for="(column,ii) in columns" :key="ii">

          <el-table-column v-if="column.dataIndex === 'name'" prop="metadata.name" :label="column.title">
          </el-table-column>
          <el-table-column v-if="column.dataIndex === 'labels'" prop="metadata.labels" :label="column.title">
            <template v-slot="{ row }">
              <!-- 遍历数组并显示每个元素 -->
              <div v-for="(item, index) in row.metadata.labels" :key="index">
                {{ item }}
              </div>
            </template>
          </el-table-column>

          <el-table-column v-if="column.dataIndex === 'image'" :prop="column.title" :label="column.title">
            <template v-slot="{ row }">
              <!-- 遍历数组并显示每个元素 -->
              <div v-for="(item, index) in row.spec.template.spec.containers" :key="index">
                {{ item.image }}
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="column.dataIndex === 'containers'" :prop="column.title" :label="column.title">
            <template v-slot="{ row }">
              <span style="font-weight:bold;">{{ row.status.availableReplicas > 0 ? row.status.availableReplicas : 0
              }} / {{ row.spec.replicas > 0 ? row.spec.replicas: 0 }}</span>
            </template>
          </el-table-column>
        </template>

        <!-- 操作按钮 -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" text @click="showEditModal(scope.row)">YAML</el-button>
            <el-button type="primary" size="small" text @click="handleScale(scope.row)">扩容</el-button>
            <el-popconfirm title="确认重启? " confirmButtonText="确认" cancelButtonText="取消"
              @confirm="restartDeployment(scope.row.metadata.name)">
              <template #reference>
                <el-button text type="warning" size="small">重启</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm title="确认删除? " confirmButtonText="确认" cancelButtonText="取消"
              @confirm="handleDelete(scope.row.metadata.name)">
              <template #reference>
                <el-button text type="warning" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>


      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
          :page-size="limit" @current-change="getData" />
      </div>

      <!-- 抽屉表单 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
          <el-form-item label="镜像名称" prop="image">
            <el-input v-model="form.title" placeholder="镜像名称"></el-input>
          </el-form-item>
          <el-form-item label="标签名称" prop="labels">
            <el-input v-model="form.content" placeholder="标签名称" type="textarea" :rows="5"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>

    <!-- 编辑YAML弹窗 -->
    <el-dialog v-model="dialogVisible" title="编辑 YAML" width="50%" :before-close="handleClose">
      <el-input type="textarea" v-model="yamlContent" :autosize="{ minRows: 10, maxRows: 20 }"
        @input="onChange"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateDeploymentYaml">确定</el-button>
      </div>
    </el-dialog>

    <!-- 调整副本弹窗 -->
    <el-dialog title="副本数调整" v-model="dialogFormReplicasVisible">
      <el-form :model="form">
        <el-form-item label="资源名称: " class="el-form-item">
          <el-input v-model="deploymentName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="副本数量: " class="el-form-item">
          <!-- <el-input v-model="scaleNum" autocomplete="off"></el-input> -->
          <el-input-number v-model="scaleNum" :min="0" :max="30" label="描述文字"></el-input-number>
          <template #reference>
            <el-icon type="info" style="margin-left: 10px; color: rgb(84, 138, 238);"></el-icon>
          </template>
          <div class="item">
            <!-- <el-tooltip class="item" effect="dark" content="Deployment实例数最小0, 最大30" placement="right-start">
              <el-button icon="el-icon-warning-outline">提示</el-button>
            </el-tooltip> -->
            <el-tooltip placement="top-start" effect="light">
              <!-- 触发提示内容 -->
              <template #content>
                <p class="content">实例数最小0, 最大30</p>
              </template>
              <span>注意:
                <el-icon color="#9a9eb1">
                  <QuestionFilled />
                </el-icon>
              </span>
            </el-tooltip>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormReplicasVisible = false">取 消</el-button>
        <el-button type="primary" @click="scaleDeployment">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script setup>
  import { ref,reactive,computed } from "vue"
  import FormDrawer from "~/components/FormDrawer.vue";
  import {
    getDeploymentsApi,
    scaleDeploymentApi,
    updateDeploymentApi,
    deleteDeploymentApi,
    deploymentDetailApi,
    restartDeploymentApi
  } from "~/api/deployment"
  import {
    toast
  } from "~/composables/util"
  import {
      getCluster,
  } from '~/composables/clustersList'
  import MainHead from "~/components/MainHead.vue";
  import json2yaml from 'json2yaml';
  import yaml2obj from 'js-yaml';
  import { QuestionFilled } from "@element-plus/icons-vue";

  const searchValue = ref('')
  const tableData = ref([])
  const loading = ref(false)
  const namespaceValue = ref('')
  const namespaceList = ref([])

  //表结构
  const columns = ref([
    {
      title: '名称',
      dataIndex: 'name'
    },
    {
      title: '标签',
      dataIndex: 'labels'
    },
    {
      title: '容器组',
      dataIndex: 'containers',
    },
    {
      title: '镜像',
      dataIndex: 'image'
    },
    {
      title: '创建时间',
      dataIndex: 'creationTimestamp'
    },
  ])

    // 编辑YAML
  // function showEditModal() {
  //   axios.get('/api/yaml').then(response => {
  //     yamlContent.value = response.data; // 获取 YAML 内容
  //     dialogVisible.value = true; // 打开弹窗
  //   }).catch(error => {
  //     console.error('Failed to fetch YAML content:', error);
  //   });
  // }

  const dialogVisible = ref(false);
  const yamlContent = ref('');

  //json转yaml方法
  function transYaml(content) {
    return json2yaml.stringify(content)
  }

  function showEditModal(e) {
    loading.value = true
    deploymentDetailData.params.deployment_name = e.metadata.name
    deploymentDetailData.params.namespace = e.metadata.namespace
    deploymentDetailData.params.cluster = getCluster()
    const deploymentDetailParams = { params: deploymentDetailData.params }
    deploymentDetailApi(deploymentDetailParams)
      .then(res => {
        //deploymentDetail = Object.assign(deploymentDetail, res.data)
        yamlContent.value = transYaml(res)
        dialogVisible.value = true
      })
      .catch(res => {
        toast(res, "error")
      })
      .finally(() => {
        loading.value = false
      })
  }



  //yaml更新
  const updateDeploymentData = reactive({
      params: {
          namespace: '',
          content: '',
          cluster: ''
      }
  })

  //编辑器内容变化时触发的方式,用于将更新的内容复制到变量中
  function onChange(val) {
      contentYaml.value = val
  }

  //yaml转对象
  function transObj(content) {
      return yaml2obj.load(content)
  }

  function updateDeploymentYaml() {
    loading.value = true
    
    //将yaml格式的deployment对象转为json
    let content = JSON.stringify(transObj(contentYaml.value))
    updateDeploymentData.params.namespace = namespaceValue.value
    updateDeploymentData.params.content = content
    updateDeploymentData.params.cluster = getCluster()
    // update请求传参为一个独立对象，和post请求不同
    // post传参：{params: deploymentListData.params}
    // update传参：updateDeploymentData.params
    updateDeploymentApi(updateDeploymentData.params)
      .then(res => {
        toast(res)
      }).catch(res => {
        toast(res, "error")
        loading.value = false
      }).finally(() => {
        getData()
        dialogVisible.value = false
        loading.value = false
      })
  }
  // 分页
  const pagination = reactive({
      showSizeChanger: true,
      showQuickJumper: true,
      total: 0,
      currentPage: 1,
      pagesize: 10,
      pageSizeOptions: ["10", "20", "50", "100"],
      showTotal: total => `共 ${total} 条`
  })

  const currentPage = ref(1)
  const total = ref(0)
  const limit = ref(10)
  const deploymentListData = reactive({
              params: {
                  filter_name: '',
                  namespace: '',
                  cluster: '',
                  page: 1,
                  limit: 10
              }
          })

  const deploymentDetailData =  reactive({
    params: {
        deployment_name: '',
        namespace: '',
        cluster: ''
    }
})
  const contentYaml = ref('')
  function ellipsis(val, len) {
    return val.length > len ? val.substring(0, len) + '...' : val
  }

  function handleAdd() {
    formDrawerRef.value.open()
  }



  function handleTableChange(val) {
      pagination.currentPage = val.current
      pagination.pagesize = val.pageSize
      getData(val.current)
  }
  function getSearchValue(val) {
      searchValue.value = val
  }
  function getNamespaceValue(val) {
      namespaceValue.value = val
  }
  function getNamespaceList(val) {
      namespaceList.value = val
  }

  // 获取数据
  function getData(){
      deploymentListData.params.filter_name = searchValue.value
      deploymentListData.params.page = currentPage.value
      deploymentListData.params.cluster = getCluster()
      deploymentListData.params.namespace = namespaceValue.value
      deploymentListData.params.limit = pagination.pagesize
      loading.value = true
      const deploymentParams = {params: deploymentListData.params}
      getDeploymentsApi(deploymentParams)
      .then(res=>{
          tableData.value = res.items
          total.value = res.total
      })
      .catch(res => {
          toast(res || 'An error occurred' , "error")
      })
      .finally(()=>{
          loading.value = false
      })
  }

  getData()



  // 表单部分
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  const form = reactive({
    image:"",
    labes:""
  })
  const rules = {
    title:[{
        required: true,
        message: 'Deployment名称不能为空',
        trigger: 'blur'
    }],
    content:[{
        required: true,
        message: 'Deployment内容不能为空',
        trigger: 'blur'
    }]
  }
  const editId = ref(0)
  const drawerTitle = computed(()=>editId.value ? "修改" : "新增")

  const handleSubmit = ()=>{
    formRef.value.validate((valid)=>{
      if(!valid) return 

      formDrawerRef.value.showLoading()

      const fun = editId.value ? updateDeployment(editId.value,form) : createDeployment(form)

      fun.then(res=>{
        toast( drawerTitle.value + "成功")
        // 修改刷新当前页，新增刷新第一页
        getData(editId.value ? false : 1)
        formDrawerRef.value.close()
      })
      .finally(()=>{
        formDrawerRef.value.hideLoading()
      })

    })
  }

  // 重置表单
  function resetForm(row = false){
    if(formRef.value) formRef.value.clearValidate()
    if(row){
      for(const key in form){
        form[key] = row[key]
      }
    }
  }

  // 新增
  const handleCreate = ()=>{
    editId.value = 0
    resetForm({
      image:"",
      labels:""
    })
    formDrawerRef.value.open()
  }

  // 编辑
  const handleEdit = (row)=>{
    editId.value = row.id
    resetForm(row)
    formDrawerRef.value.open()
  }

    //删除
  const delDeploymentData = reactive({
      params: {
          deployment_name: '',
          namespace: '',
          cluster: ''
      }
  })

  
  //删除deployment
  function handleDelete(name) {
    console.log("delete deployment name:",name)
    loading.value = true
    delDeploymentData.params.deployment_name = name
    delDeploymentData.params.namespace = namespaceValue.value
    delDeploymentData.params.cluster = getCluster()
    deleteDeploymentApi({data: delDeploymentData.params})
    .then(res => {
        toast("删除成功")
    })
    .catch(res => {
        toast(res, "error")
    })
    .finally(() => {
      getData()
      loading.value = false
    })
}

  const dialogTableReplicasVisible = ref(false);
  const dialogFormReplicasVisible = ref(false);
  const scaleNum = ref(0)
  const deploymentName = ref('')
  const scaleDeploymentData = reactive({
        params: {
            deployment_name: '',
            namespace: '',
            scale_num: '',
            cluster: ''
        }
    })

  //扩缩容的中间方法，用于赋值及打开弹出框
  function handleScale(e) {
    dialogFormReplicasVisible.value = true
    deploymentDetailData.metadata = e.metadata
    scaleNum.value = e.spec.replicas
    deploymentName.value = e.metadata.name
}

  //扩缩容
  function scaleDeployment() {
    loading.value = true
    console.log("获取deployment信息：", deploymentDetailData.metadata.name)
    console.log("获取deployment副本信息：", scaleNum.value)
    deploymentName.value = deploymentDetailData.metadata.name
    scaleDeploymentData.params.deployment_name = deploymentDetailData.metadata.name
    scaleDeploymentData.params.namespace = namespaceValue.value
    scaleDeploymentData.params.scale_num = scaleNum.value
    scaleDeploymentData.params.cluster = getCluster()
    scaleDeploymentApi(scaleDeploymentData.params)
    .then(res => {
        toast(res)
    })
    .catch(res => {
        toast(res, "error")
    })
    .finally(() => {
        getData()
        loading.value = false
        dialogFormReplicasVisible.value = false
    })
    }


  //重启
  const restartDeploymentData = reactive({
    params: {
        deployment_name: '',
        namespace: '',
        cluster: ''
    }
  })

  //重启deployment
  function restartDeployment(name) {
    loading.value = true
    restartDeploymentData.params.deployment_name = name
    restartDeploymentData.params.namespace = namespaceValue.value
    restartDeploymentData.params.cluster = getCluster()
    restartDeploymentApi(restartDeploymentData.params)
    .then(res => {
        toast(res)
    })
    .catch(res => {
        toast(res)
    })
    .finally(() => {
        getData()
        loading.value = false
    })
}



  // function  handleClose(done) {
  //   this.$confirm('确认关闭？')
  //     .then(_ => {
  //       done();
  //     })
  //     .catch(_ => {});
  // }
  function  handleClose(done) {
    dialogVisible.value = false
  }

</script>

<style scoped>
    .deployment-button {
        margin-right: 5px;
    }
    .ant-form-item {
        margin-bottom: 20px;
    }
    .el-form-item {
      width: 320px;
    }
    .item {
      margin: 10px;
    }
</style>